import { useEffect, useRef, useState } from 'react';

import { useNavigate } from 'react-router-dom';

import { PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import { ProTable as PProTable } from '@ant-design/pro-components';

import {
  equipmentAccessProtocolListByNodeTypeApi,
  type SysAccessProtocol,
} from '@/api/equipmentAccessProtocolApi';
import {
  equipmentProductDeleteApi,
  equipmentProductDetailApi,
  equipmentProductListApi,
  equipmentProductSaveOrUpdateApi,
  type ProductItem,
} from '@/api/equipmentProductApi';
import type { OperationType } from '@/constants';
import { OperationTypeList, ProductNodeType, typeToValueEnum } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

import EquipmentProductAddForm from './modules/add';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 扩展的产品项接口，包含表单需要的字段
 */
interface ExtendedProductItem extends ProductItem {
  /** 省份名称 */
  provinceName?: string;
  /** 城市名称 */
  cityName?: string;
  /** 城市选择器值 */
  cityValue?: {
    province?: string;
    city?: string;
  };
  /** 缩略图 */
  thumbnail?: string | string[];
  /** 缩略图数组（表单用） */
  thumbnailArr?: Array<{ status: string; url: string }>;
}

/**
 * API 响应类型
 */
interface ProductListResponse {
  records: ProductItem[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 设备产品管理组件
 * 提供产品的创建、编辑、删除等功能，支持接入协议管理
 */
const EquipmentProduct = () => {
  // 路由导航
  const navigate = useNavigate();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<ExtendedProductItem>({});

  // 接入协议数据
  const [accessProtocolValueEnum, setAccessProtocolValueEnum] = useState<
    Record<string, { text: string }>
  >({});

  // 加载状态
  const [_loading, _setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  /**
   * 根据节点类型获取接入协议列表
   * @param nodeType 节点类型
   */
  const fetchAccessProtocolList = async (nodeType: number) => {
    try {
      const res = await equipmentAccessProtocolListByNodeTypeApi({ nodeType });

      if (res.success && res.data && Array.isArray(res.data)) {
        // 转换为 valueEnum 格式
        const valueEnum: Record<string, { text: string }> = {};
        res.data.forEach(item => {
          if (item && item.id) {
            valueEnum[item.id] = { text: item.accessProtocolName || '未知协议' };
          }
        });
        setAccessProtocolValueEnum(valueEnum);
      } else {
        window.$message.error(res.message || '获取接入协议列表失败');
        setAccessProtocolValueEnum({});
      }
    } catch (error) {
      console.error('获取接入协议列表失败:', error);
      window.$message.error('获取接入协议列表失败，请稍后重试');
      setAccessProtocolValueEnum({});
    }
  };

  /**
   * 获取所有接入协议列表（用于初始化）
   * 获取直连设备的接入协议作为默认选项
   */
  const fetchAllAccessProtocols = async () => {
    try {
      // 获取直连设备的协议作为默认显示
      const nodeTypes = Object.values(ProductNodeType).map(item => item.value);
      const allProtocols: SysAccessProtocol[] = [];

      for (const nodeType of nodeTypes) {
        if (nodeType === ProductNodeType.DIRECT.value) {
          const res = await equipmentAccessProtocolListByNodeTypeApi({ nodeType });
          if (res.success && res.data) {
            allProtocols.push(...res.data);
          }
        }
      }

      // 去重处理
      const uniqueProtocols = allProtocols.filter(
        (protocol, index, self) => index === self.findIndex(p => p.id === protocol.id)
      );

      // 转换为 valueEnum 格式
      const valueEnum: Record<string, { text: string }> = {};
      if (uniqueProtocols && Array.isArray(uniqueProtocols)) {
        uniqueProtocols.forEach(item => {
          if (item && item.id) {
            valueEnum[item.id] = { text: item.accessProtocolName || '未知协议' };
          }
        });
      }
      setAccessProtocolValueEnum(valueEnum);
    } catch (error) {
      console.error('获取所有接入协议列表失败:', error);
      window.$message.error('获取接入协议列表失败，请稍后重试');
    }
  };

  // 组件初始化时获取所有协议
  useEffect(() => {
    fetchAllAccessProtocols();
  }, []);

  /**
   * 获取产品列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // 移除无效参数，避免传递空值
      const validParams = Object.entries(params).reduce(
        (acc, [key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            acc[key] = value;
          }
          return acc;
        },
        {} as Record<string, unknown>
      );

      const res = await equipmentProductListApi(validParams);

      if (res.success && res.data) {
        const responseData = res.data as unknown as ProductListResponse;
        return {
          success: true,
          data: Array.isArray(responseData?.records) ? responseData.records : [],
          total: responseData?.total ?? 0,
        };
      } else {
        window.$message.error(res.message || '获取产品列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
      window.$message.error('获取产品列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };
  /**
   * 删除产品
   * @param record 产品记录
   */
  const handleDelete = async (record: ProductItem) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：产品ID不存在');
      return;
    }

    try {
      const res = await equipmentProductDeleteApi({ id: String(record.id) });
      if (res.success) {
        window.$message.success('产品删除成功');
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除产品失败:', error);
      window.$message.error('删除失败，请稍后重试');
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<ProductItem>[] = [
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      copyable: false,
    },
    {
      title: '节点类型',
      dataIndex: 'nodeType',
      key: 'nodeType',
      valueEnum: typeToValueEnum(ProductNodeType),
      ellipsis: true,
      search: true,
      fieldProps: {
        onChange: (value: number) => {
          if (value) {
            fetchAccessProtocolList(value);
          } else {
            // setAccessProtocolValueEnum({});
          }
        },
      },
    },
    {
      title: '接入协议',
      dataIndex: 'accessProtocolId',
      key: 'accessProtocolId',
      search: true,
      valueEnum: accessProtocolValueEnum,
      render: (_, record) => record.accessProtocolName || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 220,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              if (record.id) {
                navigate(`/equipment/product/detail/${record.id}`);
              }
            }}
          >
            查看
          </AButton>
          <AButton
            type="link"
            size="small"
            onClick={async () => {
              if (!record.id) {
                window.$message.error('产品ID不存在，无法编辑');
                return;
              }

              try {
                const res = await equipmentProductDetailApi({ id: String(record.id) });
                if (res.success && res.data) {
                  const apiData = res.data as ExtendedProductItem;
                  const newData: ExtendedProductItem = {
                    ...record,
                    ...apiData,
                  };

                  // 处理城市数据
                  const cityValue = {
                    province: newData.provinceName,
                    city: newData.cityName,
                  };

                  // 处理缩略图数据
                  let thumbnailArr: Array<{ status: string; url: string }> = [];
                  if (newData.thumbnail) {
                    try {
                      const thumbnailData =
                        typeof newData.thumbnail === 'string'
                          ? JSON.parse(newData.thumbnail)
                          : newData.thumbnail;

                      if (Array.isArray(thumbnailData)) {
                        thumbnailArr = thumbnailData.map(url => ({
                          status: 'done',
                          url: url,
                        }));
                      }
                    } catch (error) {
                      console.error('解析缩略图失败:', error);
                      window.$message.warning('缩略图数据解析失败');
                    }
                  }

                  const formData: ExtendedProductItem = {
                    ...newData,
                    cityValue,
                    thumbnailArr,
                  };

                  setCurrentRecord(formData);
                  setDrawerType('EDIT');
                  setDrawerShow(true);
                  form.setFieldsValue(formData);
                } else {
                  window.$message.error(res.message || '获取产品详情失败');
                }
              } catch (error) {
                console.error('获取产品详情失败:', error);
                window.$message.error('获取产品详情失败，请稍后重试');
              }
            }}
          >
            编辑
          </AButton>
          <APopconfirm
            title="您确定要删除吗？"
            description={`请确认【${record.productName || ''}】产品下已无关联设备，否则无法删除`}
            onConfirm={() => {
              handleDelete(record);
            }}
            okType="danger"
            okText="确认"
            cancelText="取消"
          >
            <AButton type="link" size="small" danger>
              删除
            </AButton>
          </APopconfirm>
        </ASpace>
      ),
    },
  ];
  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({});
    setDrawerType('ADD');
    setDrawerShow(false);
    form.resetFields();
  };

  /**
   * 处理表单提交
   * 支持新增和编辑两种模式
   */
  const handleSubmit = async () => {
    try {
      setSubmitting(true);

      const params = await form.validateFields();
      const requestParams = {
        ...currentRecord,
        ...params,
      };

      // 处理城市数据
      if (requestParams.cityValue) {
        requestParams.provinceName = requestParams.cityValue.province;
        requestParams.cityName = requestParams.cityValue.city;
        delete requestParams.cityValue; // 删除临时字段
      }

      // 处理缩略图数据
      if (requestParams.thumbnailArr && Array.isArray(requestParams.thumbnailArr)) {
        requestParams.thumbnail = JSON.stringify(requestParams.thumbnailArr.map(v => v.url));
        delete requestParams.thumbnailArr; // 删除临时字段
      }

      const res = await equipmentProductSaveOrUpdateApi(requestParams);
      if (res.success) {
        const successMessage = drawerType === 'ADD' ? '产品创建成功' : '产品更新成功';
        window.$message.success(successMessage);
        handleDrawerClose();
        actionRef.current?.reload(); // 刷新表格数据
      } else {
        window.$message.error(res.message || '操作失败');
      }
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error instanceof Error) {
        window.$message.error(`操作失败：${error.message}`);
      } else {
        window.$message.error('表单验证失败，请检查输入');
      }
    } finally {
      setSubmitting(false);
    }
  };
  return (
    <div className="page-wrapper">
      <ADrawer
        destroyOnHidden
        title={`产品${OperationTypeList[drawerType].label}`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType !== 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit} loading={submitting}>
                  {submitting ? '提交中...' : '提交'}
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <div className="w-full px-8 py-8">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
            <EquipmentProductAddForm form={form} data={currentRecord as ProductItem} />
          </AForm>
        </div>
      </ADrawer>
      <div className="page-title">
        <div className="page-main-title">产品列表</div>
        <div className="page-sub-title">产品定义为具有同样属性的物联设备的集合</div>
      </div>
      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            <PProTable<ProductItem>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton
                  key="add"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => {
                    form.resetFields();
                    setCurrentRecord({});
                    setDrawerType('ADD');
                    setDrawerShow(true);
                    // 设置默认值
                    setTimeout(() => {
                      form.setFieldsValue({
                        source: 0, // 默认创建方式
                      });
                    }, 100);
                  }}
                >
                  新增产品
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default EquipmentProduct;
